package com.tjvib.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.View;

import com.tjvib.TJVIBAPP;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.Document;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

/**
 * 导出word
 */
public class PoiUtil {
    /**
     * 替换模板中的字段
     *
     * @param context      上下文
     * @param outputName   输出文件名
     * @param replacements 替换的字段及对应的值
     */
    public static void replaceFieldsWithImage2(Bitmap bitmap, Context context, String method,
                                     String outputName, Map<String, String> replacements) {
        try {
            // 从assets目录中读取模板文件
            XWPFDocument doc = new XWPFDocument(context.getAssets().open(method + ".docx"));

            XWPFParagraph paragraph = doc.createParagraph();
            XWPFRun run = paragraph.createRun();
            run.setText("图像：\n");

            // 将Bitmap转换为字节数组
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
            byte[] byteArray = stream.toByteArray();

            // 插入图片
            InputStream is = new ByteArrayInputStream(byteArray);
            run.addPicture(is, Document.PICTURE_TYPE_PNG, method + "_image.png",
                    Units.toEMU(300), Units.toEMU(200));

            stream.close();

            // 替换字段
            replaceParagraphs(doc.getParagraphs(), replacements);
            replaceTables(doc.getTables(), replacements);

            // 保存文件到设备目录
            saveDocumentToDirectory(doc, method + "_" + outputName);
        } catch (IOException e) {
            LogUtil.e("replaceFields: IOException", e);
        } catch (InvalidFormatException e) {
            LogUtil.e("replaceFields: InvalidFormatException", e);
        }
    }


    public static void replaceFieldsWithImage(Bitmap bitmap, Context context, String method,
                                              String outputName, Map<String, String> replacements) {
        try(InputStream inputStream = context.getAssets().open(method + ".docx")) {
            XWPFDocument doc = new XWPFDocument(inputStream);// 从assets目录中读取模板文件
            XWPFParagraph paragraph = doc.createParagraph();
            XWPFRun run = paragraph.createRun();
            if(bitmap != null) {// 将Bitmap转换为字节数组
                run.setText("图像：\n");
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
                byte[] byteArray = stream.toByteArray();
                InputStream is = new ByteArrayInputStream(byteArray);
                run.addPicture(is, Document.PICTURE_TYPE_PNG, method + "_image.png",
                        Units.toEMU(300), Units.toEMU(200));
                stream.close();// 释放ByteArrayOutputStream资源
                bitmap.recycle();
            }
            replaceParagraphs(doc.getParagraphs(), replacements);// 替换字段
            saveDocumentToDirectory(doc, method + "_" + outputName);// 保存文件到设备目录
        } catch (IOException | InvalidFormatException e) {
            LogUtil.e("Exception", e);
        }
    }


    /**
     * 替换段落中的字段
     *
     * @param paragraphs
     * @param replacements
     */
    private static void replaceParagraphs(List<XWPFParagraph> paragraphs, Map<String, String> replacements) {
        for (XWPFParagraph paragraph : paragraphs) {
            List<XWPFRun> runs = paragraph.getRuns();
            for (XWPFRun run : runs) {
                String text = run.getText(0);
                if (text != null) {
                    for (Map.Entry<String, String> entry : replacements.entrySet()) {
                        text = text.replace(entry.getKey(), entry.getValue());
                    }
                    run.setText(text, 0);
                }
            }
        }
    }

    /**
     * 替换表格中的字段
     *
     * @param tables
     * @param replacements
     */
    private static void replaceTables(List<XWPFTable> tables, Map<String, String> replacements) {
        XWPFTable table = tables.get(0);
        table.getRow(1).getCell(1).setText(replacements.get("【峰值AccX】"));
        table.getRow(2).getCell(1).setText(replacements.get("【峰值AccY】"));
        table.getRow(3).getCell(1).setText(replacements.get("【峰值AccZ】"));
        table.getRow(1).getCell(2).setText(replacements.get("【最大1rmsAccX】"));
        table.getRow(2).getCell(2).setText(replacements.get("【最大1rmsAccY】"));
        table.getRow(3).getCell(2).setText(replacements.get("【最大1rmsAccZ】"));
        table.getRow(1).getCell(3).setText(replacements.get("【最大10rmsAccX】"));
        table.getRow(2).getCell(3).setText(replacements.get("【最大10rmsAccY】"));
        table.getRow(3).getCell(3).setText(replacements.get("【最大10rmsAccZ】"));
        table.getRow(1).getCell(4).setText(replacements.get("【RMSAccX】"));
        table.getRow(2).getCell(4).setText(replacements.get("【RMSAccY】"));
        table.getRow(3).getCell(4).setText(replacements.get("【RMSAccZ】"));

//        for (XWPFTable table : tables) {
//            for (XWPFTableRow row : table.getRows()) {
//                for (XWPFParagraph paragraph : row.getTableCells().get(0).getParagraphs()) {
//                    List<XWPFRun> runs = paragraph.getRuns();
//                    for (XWPFRun run : runs) {
//                        String text = run.getText(0);
//                        if (text != null) {
//                            for (Map.Entry<String, String> entry : replacements.entrySet()) {
//                                text = text.replace(entry.getKey(), entry.getValue());
//                            }
//                            run.setText(text, 0);
//                        }
//                    }
//                }
//            }
//        }
    }


    /**
     * 保存手机设备本地
     *
     * @param doc
     * @param outputName
     */
    private static void saveDocumentToDirectory(XWPFDocument doc, String outputName) {
        File downloadDirectory = TJVIBAPP.getApplication().getExternalFilesDir(null);
        File file = new File(downloadDirectory, outputName);
        OutputStream os = null;
        try {
            os = new FileOutputStream(file);
            doc.write(os);
            LogUtil.d("saveDocumentToDirectory: Saved to " + file.getAbsolutePath());
        } catch (IOException e) {
            LogUtil.e("saveDocumentToDirectory: IOException", e);
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                LogUtil.e("saveDocumentToDirectory: IOException", e);
            }
        }
    }


    /**
     * 保存控件view的图片
     *
     * @param view
     * @return
     */
    public static Bitmap loadBitmapFromView(View view) {
        Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);

        Canvas canvas = new Canvas(bitmap);
        canvas.drawColor(Color.WHITE);

        view.layout(0, 0, view.getWidth(), view.getHeight());
        view.draw(canvas);

        return bitmap;
    }
}
